import { type CollectionEntry, getCollection } from "astro:content";
import type { WebResult } from "@/types/web-result";
import httpRequest from "./http";
import { getCategoryUrl } from "./url-utils";

async function getRawSortedPosts() {
	const allBlogPosts = await getCollection("posts", ({ data }) => {
		return import.meta.env.PROD ? data.draft !== true : true;
	});

	const sorted = allBlogPosts.sort((a, b) => {
		// 首先按置顶状态排序，置顶文章在前
		if (a.data.pinned && !b.data.pinned) return -1;
		if (!a.data.pinned && b.data.pinned) return 1;

		// 如果置顶状态相同，则按发布日期排序
		const dateA = new Date(a.data.published);
		const dateB = new Date(b.data.published);
		return dateA > dateB ? -1 : 1;
	});
	return sorted;
}

export async function getSortedPosts() {
	const sorted = await getRawSortedPosts();

	for (let i = 1; i < sorted.length; i++) {
		sorted[i].data.nextSlug = sorted[i - 1].slug;
		sorted[i].data.nextTitle = sorted[i - 1].data.title;
	}
	for (let i = 0; i < sorted.length - 1; i++) {
		sorted[i].data.prevSlug = sorted[i + 1].slug;
		sorted[i].data.prevTitle = sorted[i + 1].data.title;
	}

	return sorted;
}
export type PostForList = {
	slug: string;
	data: CollectionEntry<"posts">["data"];
};
export async function getSortedPostsList(): Promise<PostForList[]> {
	const sortedFullPosts = await getRawSortedPosts();

	// delete post.body
	const sortedPostsList = sortedFullPosts.map((post) => ({
		slug: post.slug,
		data: post.data,
	}));

	return sortedPostsList;
}

export type Tag = {
	name: string;
	count: number;
};

// export async function getTagList(): Promise<Tag[]> {
// 	const allBlogPosts = await getCollection<"posts">("posts", ({ data }) => {
// 		return import.meta.env.PROD ? data.draft !== true : true;
// 	});

// 	const countMap: { [key: string]: number } = {};
// 	allBlogPosts.map((post: { data: { tags: string[] } }) => {
// 		post.data.tags.map((tag: string) => {
// 			if (!countMap[tag]) countMap[tag] = 0;
// 			countMap[tag]++;
// 		});
// 	});

// 	// sort tags
// 	const keys: string[] = Object.keys(countMap).sort((a, b) => {
// 		return a.toLowerCase().localeCompare(b.toLowerCase());
// 	});

// 	return keys.map((key) => ({ name: key, count: countMap[key] }));
// }
export async function getTagList(): Promise<Tag[]> {
	return await httpRequest<
		WebResult<
			{
				id: number;
				name: string;
				description: string | null;
				create_time: Date | null;
			}[]
		>
	>({
		url: "/api/extra/tag/list",
	}).then(async (result) => {
		const tagList: Tag[] = [];
		const data = result?.data || [];
		for (const tag of data) {
			const articleIDList = await httpRequest<WebResult<number[]>>({
				url: `/api/article/tag/${tag.id}/article/ids`,
			}).then((result) => {
				return result?.data || [];
			});
			tagList.push({
				name: tag.name,
				count: articleIDList.length,
			});
		}

		return tagList;
	});
}

export type Category = {
	name: string;
	count: number;
	url: string;
};

// export async function getCategoryList(): Promise<Category[]> {
// 	const allBlogPosts = await getCollection<"posts">("posts", ({ data }) => {
// 		return import.meta.env.PROD ? data.draft !== true : true;
// 	});
// 	const count: { [key: string]: number } = {};
// 	allBlogPosts.map((post: { data: { category: string | null } }) => {
// 		if (!post.data.category) {
// 			const ucKey = i18n(I18nKey.uncategorized);
// 			count[ucKey] = count[ucKey] ? count[ucKey] + 1 : 1;
// 			return;
// 		}

// 		const categoryName =
// 			typeof post.data.category === "string"
// 				? post.data.category.trim()
// 				: String(post.data.category).trim();

// 		count[categoryName] = count[categoryName] ? count[categoryName] + 1 : 1;
// 	});

// 	const lst = Object.keys(count).sort((a, b) => {
// 		return a.toLowerCase().localeCompare(b.toLowerCase());
// 	});

// 	const ret: Category[] = [];
// 	for (const c of lst) {
// 		ret.push({
// 			name: c,
// 			count: count[c],
// 			url: getCategoryUrl(c),
// 		});
// 	}
// 	return ret;
// }

export async function getCategoryList(): Promise<Category[]> {
	return await httpRequest<
		WebResult<
			{
				id: number;
				name: string;
				description: string | null;
				create_time: Date | null;
			}[]
		>
	>({
		url: "/api/article/sort/list",
	}).then(async (result) => {
		const categoryList: Category[] = [];
		const data = result?.data || [];

		for (const sort of data) {
			const count = await httpRequest<WebResult<number>>({
				url: `/api/article/sort/count/article/${sort.id}`,
			}).then((result) => {
				return result?.data || 0;
			});
			categoryList.push({
				name: sort.name,
				count: count,
				url: getCategoryUrl(sort.id.toString()),
			});
		}
		return categoryList;
	});
}
